//
//  VietNewsArticleViewController.m
//  VietNews
//
//  Created by Nguyen .a.Hph on 22/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "VietNewsArticleViewController.h"
#import "XHTMLParser.h"
#import "CellEntry.h"
#import "Util.h"
#import <QuartzCore/QuartzCore.h>

#define kAppIconHeight 60

@interface VietNewsArticleViewController ()

@end

@implementation VietNewsArticleViewController
@synthesize nextSectionUrl;
@synthesize detailViewController = _detailViewController;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)configureView{
    NSLog(@"%s",__FUNCTION__);
    
    self.cellIdentifier = @"articleCell";
    CellEntry *parentObj = (CellEntry *)self.detailItem;
    [self.navigationItem setTitle:parentObj.title];
    [XHTMLParser getArticlesByUrl:parentObj.url site:self.siteItem tableVC:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.detailViewController = (VietNewsDetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
    
    [self configureView];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

#pragma mark - Table view data source
/*
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    int rows = [super tableView:tableView numberOfRowsInSection:section];
    //if (rows>0)
    //    return rows+1;
    return rows;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.objects count]>0 && indexPath.row == [self.objects count]){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier];
        if(cell==nil){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.cellIdentifier];
        }
        cell.textLabel.center = cell.center;
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.text = @"Load More...";
        //cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
 */

-(void)displayCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *) indexPath withData:(id)obj{
    //load/display image
    CellEntry *item = (CellEntry *)obj;
    cell.textLabel.text = item.title;
    cell.textLabel.numberOfLines = 2;
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.detailTextLabel.text = item.time;
    if (!item.img){//no image
        item.image = [UIImage imageNamed:@"spacer.png"];
    }
    if (!item.image){
        if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
        {
            [self startIconDownload:item forIndexPath:indexPath];
        }
        // if a download is deferred or in progress, return a placeholder image
        cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
    }
    else {
        cell.imageView.image = item.image;
    }
    /*
    NSString *imageUrl = [Util getAbsoluteUrl:item.img parentUrl:self.detailItem];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[[NSURL alloc] initWithString:imageUrl]]];
    [cell.imageView setImage:image];
    */
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //44.0 + (numberOfLines - 1) * 19.0
    return 80.0;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        CellEntry *object = [self.objects objectAtIndex:indexPath.row];
        NSArray *urlArr = [self getUrlArray];
        
        [self.detailViewController setSiteItem:self.siteItem];
        [self.detailViewController setParentObjects:urlArr];
        [self.detailViewController setDetailItem:object];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    if ([[segue identifier] isEqualToString:@"showArticleDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        CellEntry *object = [self.objects objectAtIndex:indexPath.row];
        NSArray *urlArr = [self getUrlArray];
        
        [[segue destinationViewController] setSiteItem:self.siteItem];
        [[segue destinationViewController] setParentObjects:urlArr];
        [[segue destinationViewController] setDetailItem:object];
    }
}

- (NSArray *)getUrlArray{
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for(CellEntry *cell in self.objects)
        [resultArr addObject:cell.url];
    return resultArr;
}


#pragma mark - UIScrollViewDelegate

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([self.objects count] > 0)
    {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            CellEntry *item = [self.objects objectAtIndex:indexPath.row];
            if (!item.image) // avoid the app icon download if the app already has an icon
            {
                [self startIconDownload:item forIndexPath:indexPath];
            }
        }
    }
}

- (void)startIconDownload:(CellEntry *)item forIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    CellEntry *parentObj = (CellEntry *)self.detailItem;
    NSString *imagePath = [Util getAbsoluteUrl:item.img parentUrl:parentObj.url];
    NSURL *nsUrl = [[NSURL alloc] initWithString:imagePath];
    dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader",NULL);
    dispatch_async(downloadQueue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:nsUrl];
        UIImage *image = [UIImage imageWithData:imageData];
        if (image.size.width != kAppIconHeight && image.size.height != kAppIconHeight)
        {
            CGSize itemSize = CGSizeMake(kAppIconHeight, kAppIconHeight);
            UIGraphicsBeginImageContext(itemSize);
            CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
            
            //round image
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSaveGState(context);
            [Util addRoundedRectToPath:context rect:imageRect ovalWidth:8 ovalHeight:8];
            CGContextClip(context);
            [image drawInRect:imageRect];
            CGContextRestoreGState(context);
            
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            item.image = image;
            cell.imageView.image = item.image;
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        });
    });
    dispatch_release(downloadQueue);

}

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}


#pragma mark - Pagination

- (void)setupTableViewFooter 
{
    self.tableView.tableFooterView = nil;
    if ([self.nextSectionUrl length]==0)
        return;
    // set up label
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    footerView.backgroundColor = [UIColor clearColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    label.font = [UIFont boldSystemFontOfSize:16];
    label.textColor = [UIColor lightGrayColor];
    label.textAlignment = UITextAlignmentCenter;
    label.text = @"More...";
    footerLabel = label;
    [footerView addSubview:label];
    
    // set up activity indicator
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.center = CGPointMake(110, 22);
    activityIndicatorView.hidesWhenStopped = YES;
    
    activityIndicator = activityIndicatorView;
    [footerView addSubview:activityIndicatorView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(footerViewTapHandle:)];
    [tapGesture setNumberOfTapsRequired:1];
    [footerView addGestureRecognizer:tapGesture];
    
    self.tableView.tableFooterView = footerView;
}

- (void)footerViewTapHandle:(UITapGestureRecognizer *)sender{
    NSLog(@"tap on footer");
    CellEntry *parentObj = (CellEntry *)self.detailItem;
    parentObj.url = self.nextSectionUrl;
    [XHTMLParser getArticlesByUrl:parentObj.url site:self.siteItem tableVC:self];
    [activityIndicator startAnimating];
}

#pragma mark - QueryRemoteDataDelegate
- (void)didReceiveRemoteData:(id)remoteData from:(id)remoteSender{
    if (!self.objects){
        self.objects = [[NSMutableArray alloc] init];
    }
    [self.objects addObjectsFromArray:remoteData];
    
    //TODO optimize reload
    [self.tableView reloadData];
    [self setupTableViewFooter];
    [activityIndicator stopAnimating];
}
@end
